from tornado.web import HTTPError
import re


class ArgumentError(HTTPError):
    """Exception raised by `RequestHandler.get_argument`.

    This is a subclass of `HTTPError`, so if it is uncaught a 400 response
    code will be used instead of 500 (and a stack trace will not be logged).

    .. versionadded:: 3.1
    """

    def __init__(self, code, arg_name):
        super(ArgumentError, self).__init__(code, '%s' % arg_name, reason='%s' % arg_name)
        self.arg_name = arg_name


class base_verify(object):

    def __init__(self, is_none=True, _type=str, length=0, default=None):
        self.is_none = is_none
        self._type = _type
        self.length = length
        self._default = default

    # 初始验证
    def initialize(self, name, argument):
        if not self.is_none and argument is None:
            raise ArgumentError(code=4004, arg_name="%s 不能为空" % name)
        if not isinstance(argument, self._type) and not self.is_none:
            if (self._type.__name__ == "float") and isinstance(argument, int):  # 当类型为float时过滤掉int类型
                pass
            else:
                raise ArgumentError(code=4004, arg_name="%s 必须是一个%s类型" % (name, self._type))
        if isinstance(argument, str) and 0 < self.length < argument.__len__():
            raise ArgumentError(code=4004, arg_name="%s 长度不能超过%s个字符" % (name, self.length))

    def verify(self, name, argument):
        pass

    @property
    def default(self):
        return self._default


class mail_verify(base_verify):
    """
    邮箱验证
    """
    def verify(self, name, argument):
        if name:
            if re.match(r'^[0-9a-zA-Z_]{0,19}@[0-9a-zA-Z]{1,13}\.[com,net]{1,3}$', argument):
                pass
            else:
                raise ArgumentError(code=4004, arg_name="邮箱格式错误")


class phone_verify(base_verify):
    """
    手机号验证
    """
    def verify(self, name, argument):
        if name:
            if str(argument)[0:1] != "1":
                raise ArgumentError(code=4004, arg_name="手机号格式错误")
            if str(argument).__len__() != 11:
                raise ArgumentError(code=4004, arg_name="手机号格式错误")
